package io.codegeneratetool.util;

import io.codegeneratetool.core.FieldInfo;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Embedded;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
 

public class FieldUtil {

	/**
	 * 说明：获取所有字段信息
	 * @author subook 创建时间2012-10-18下午9:01:40
	 * @param 
	 */
	public static <T> List<FieldInfo> getFields(T t , String parentName){
		 List<FieldInfo> fieldInfos = new ArrayList<FieldInfo>();
		Field[] declaredFields = t.getClass().getDeclaredFields();
		String className =  StringUtils.getSpringName(t.getClass());
		for (Field field : declaredFields) {
			 if(field.getAnnotation(OneToMany.class)!=null
					 || field.getAnnotation(ManyToMany.class)!=null
					 ){
				 continue;
			 }
			 
			 //不受控的字段不显示在界面
			 if(field.getAnnotation(Transient.class)!=null ){
				 continue;
			 }
			Embedded annotation = field.getAnnotation(Embedded.class);
			if(annotation!=null ){
				if(!"entityauditing".equals(field.getType().getSimpleName().toLowerCase())){
					try {
						List<FieldInfo> f =  getFields(field.getType().newInstance() , className);
						fieldInfos.addAll(f);
					} catch ( Exception e) {
						e.printStackTrace();
					}
				}
			}else{
				FieldInfo fieldInfo = new FieldInfo();
				fieldInfo.setField(field);
				String className2 = (parentName==null? "": parentName+".") +className;
				fieldInfo.setClassName(className2);
				fieldInfo.setFieldName(field.getName());
				String normalCssClass = (className2+"."+field.getName()).replaceAll("\\.","_");
				String fieldTypeName = field.getType().getName();
				if(field.getAnnotation(Temporal.class)!=null || fieldTypeName.indexOf(".Date")>0 || fieldTypeName.indexOf(".Timestamp")>0){
					normalCssClass = normalCssClass + " datepick_short ";
					fieldInfo.addCustomAttribute("dateformat","yyyy-MM-dd");
				} 
				fieldInfo.setCssClass(normalCssClass );
				Annotation[] annotations = field.getAnnotations();
				for (Annotation annotation2 : annotations) {
					fieldInfo.getValidateAttributes().add(processValidAnnotation(annotation2));
				}
				fieldInfos.add(fieldInfo);
			}
		}
		
		return fieldInfos;
	}
	
	private static String processValidAnnotation(Annotation annotation){
		if(annotation instanceof NotNull){
			return " required";
		}
		
		
		
		 
		return null;
	}
	
	
	
	
	
	
}
